package com.upcode.weighing.oauthserver.exception;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zhuyanwei
 */
@JsonSerialize(using = CustomOauthExceptionSerializer.class)
public class CustomOauthException extends OAuth2Exception {

    private String message;
    private Integer code;
    private Integer status;

    private String timestamp;
    private String exception;
    public CustomOauthException(String msg) {
        super(msg);
    }
    public CustomOauthException(String msg, Throwable t) {
        super(msg, t);
        if(t instanceof OAuth2Exception) {
            setCommanValue(t);
            code = 4010;
            message = "输入密码错误！";
            status=401;
        }else if(t instanceof AuthenticationException){
            setCommanValue(t);
            code = 4010;
            status=401;
        } else {
            setCommanValue(t);
            code = 5000;
            status=500;
        }
    }

    private void setCommanValue(Throwable t) {
        exception=t.getClass().getName();
        message = t.getMessage();
        if(message!=null  && message.contains("MISCONF Redis is configured to save RDB snapshots")){
            message="token缓存已满,请联系管理员";
        }
        timestamp= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    public String getMessage() {
        return message;
    }
    public Integer getCode() {
        return code;
    }
    public Integer getStatus() {
        return status;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public String getException() {
        return exception;
    }
}
